#include <commands/client/c_request_texture_tile.h>
#include <commands\server\s_send_texture_tile.h>
#include <app\states\connectionState.h>
#include <app\states\textureTileState.h>

REGISTER_COMMAND(CLIENT_REQUEST_TEXTURE_TILE, c_request_texture_tile)

c_request_texture_tile::c_request_texture_tile() : command(0, NULL) {
  x = 0;
  y = 0;
  level = 0;
}

c_request_texture_tile::c_request_texture_tile(unsigned int _type_id, streamingConnection *_connection) : command(_type_id, _connection) {
  x = 0;
  y = 0;
  level = 0;
}

void 
c_request_texture_tile::setData(int x, int y, int level) {
  this->x = x;
  this->y = y;
  this->level = level;
}

void
c_request_texture_tile::decode(stringstream &bytes_stream, int size) {
#ifdef SERVER

  #ifdef DEBUG_INFO
  std::cerr << "SERVER DECODE: c_request_texture_tile" << std::endl;
  #endif

  streamingConnection *conn = getconnection();
  textureTileState *ttstate = GET_STATE(textureTileState, conn);

  bytes_stream >> x;
  bytes_stream >> y;
  bytes_stream >> level;
/*
  ttstate->

  s_send_texture_tile *cmd = static_cast<s_send_texture_tile *>(commandFactory::instance().createCommand(SERVER_SEND_TEXTURE_TILE, conn));
  
  if (mfstate) {
        int size;
        unsigned char *data = mfstate->getRawData(size);
        cmd->setData(data, size);
        cmd->execute();
        delete cmd;
      }
    }
  }*/

#endif
}

void 
c_request_texture_tile::execute() {
#ifdef CLIENT
  
  #ifdef DEBUG_INFO
  std::cerr << "CLIENT EXECUTE: c_request_texture_tile" << std::endl;
  #endif

  unsigned int *id = new unsigned int[1];
  unsigned int *total_size = new unsigned int[1];
  unsigned int data_size;

  total_size[0] = sizeof(unsigned int); // total size itself

  id[0] = getTypeId();
  total_size[0] += sizeof(unsigned int); // id size

  stringstream bytes(ios::out | ios::in | ios::binary);
   bytes << x << endl;
   bytes << y << endl;
   bytes << level << endl;
   bytes.seekg(0, ios::end);
  data_size = bytes.tellg();
  unsigned char *data = new unsigned char[data_size];
  bytes.seekg(0, ios::beg);
  bytes.read((char *) data, data_size);

  total_size[0] += data_size;
  
  sendBytes(total_size, sizeof(unsigned int));
  sendBytes(id, sizeof(unsigned int));

  bytes.seekg(0, ios::beg);
  sendBytes(data, data_size);
  
#endif
}
